﻿<%@ WebHandler Language="C#" Class="GovernmentOfficeProject.handler.CalendarDatafeed" %>

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using GovernmentOfficeProject.LevelDataAccessModel;
using GovernmentOfficeProject.SysTools;
using GovernmentOfficeProject.LevelDataAccess;
using System.Text;
using System.Web.SessionState;
using GovernmentOfficeProject.LevelBusinessLogic;

namespace GovernmentOfficeProject.handler
{
    /// <summary>
    /// 日程数据处理
    /// </summary>
    public partial class CalendarDatafeed : IHttpHandler, IRequiresSessionState
    {
        private string method = "";
        private decimal userId = 1;
        private HttpContext _context;
        private bool isLdCalendar = false; 
        public void ProcessRequest(HttpContext context)
        {
             //权限判断
            if (SystemContext.CurrentUserID == 0)
            {
                context.Response.Redirect("~/Login.htm?FromUrl=" + HttpUtility.UrlEncode(context.Request.Url.AbsoluteUri));
            }
            else
            {
                SystemContext.CurrentUserID = SystemContext.CurrentUserID;
            }
            context.Response.ContentType = "text/plain";
            _context = context;
            //判断是否为领导日程
            isLdCalendar = _context.Request.Params["ldCalendar"] != null ? true : false;            
            //日程用户 
            userId = Convert.ToDecimal(_context.Request.Params["userId"]);
                        
            method = _context.Request.Params["method"];
            string ret = "";
            switch (method)
            {
                case "add":
                    ret = AddCalendar();
                    break;
                case "list":
                    ret = ListCalendarJsionDate(_context.Request.Params["showdate"], _context.Request.Params["viewtype"]);
                    break;
                case "gridlist":
                    ret = ListCalendarJsionDateForListView();
                    break;
                case "update":
                    ret = UpdateCalendar(_context.Request.Params["calendarId"], _context.Request.Params["CalendarStartTime"], _context.Request.Params["CalendarEndTime"]);
                    break;
                case "remove":
                    ret = RemoveCalendar(_context.Request.Params["calendarId"]);
                    break;
                case "adddetails":
                    if (_context.Request.Params["id"] != null && decimal.Parse(_context.Request.Params["id"]) > 0)
                    {
                        ret = UpdateDetailedCalendar(decimal.Parse(_context.Request.Params["id"]));
                    }
                    else
                    {
                        ret = AddDetailedCalendar();
                    }
                    break;
                case "smsProview":
                    ret = SmsPriview(this.getCalendarDetailed());
                    break;
            }
            //JSON 数据
            _context.Response.Write(ret);
            _context.Response.End();
        }

        /// <summary>
        /// 获得日程列表  JSON格式
        /// </summary>
        /// <param name="showdate"></param>
        /// <param name="viewtype"></param>
        /// <returns></returns>
        private string ListCalendarJsionDate(string showdate, string viewtype)
        {
            string startDateStr = "";
            string endDateStr = "";
            DateTime date = DateTime.Parse(showdate);
            //根据视图类型，获得时间段
            switch (viewtype)
            {
                case "month":
                    startDateStr = DateTimeUtil.Date2String(DateTimeUtil.GetFirstDayForMonth(date), "yyyy-MM-dd 00:00:00");
                    endDateStr = DateTimeUtil.Date2String(DateTimeUtil.GetLastDayForMonth(date), "yyyy-MM-dd HH:mm:ss");
                    break;
                case "week":
                    DateTime start = DateTimeUtil.FormatDate(DateTimeUtil.GetThisDateMonday(date), "yyyy-MM-dd 00:00:00");
                    startDateStr = DateTimeUtil.Date2String(start, "yyyy-MM-dd HH:mm:ss");
                    endDateStr = DateTimeUtil.Date2String(start.AddDays(7).AddSeconds(-1), "yyyy-MM-dd HH:mm:ss");
                    break;
                case "day":
                    startDateStr = DateTimeUtil.Date2String(date, "yyyy-MM-dd 00:00:00");
                    endDateStr = DateTimeUtil.Date2String(date, "yyyy-MM-dd 23:59:59");
                    break;
            }

            //日程的Json格式对象

            CalendarJsonEntity cje = new CalendarJsonEntity();
            cje.issort = true;
            cje.start = startDateStr;
            cje.end = endDateStr;
            cje.error = null;

            DAL_SME_SCHEDULE dss = new DAL_SME_SCHEDULE();
            List<Entity_SME_Schedule> list = dss.getScheduleListByUserIdAndDate(userId, startDateStr, endDateStr,isLdCalendar);
            cje.events = new Object[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                Entity_SME_Schedule schedule = list[i];
                //cje.events.
                cje.events[i] = new object[]{
                    schedule.SceID,
                    schedule.Title,
                    schedule.StartTime,
                    schedule.EndTime,
                    schedule.IsAllDayEvent,
                    0,
                    0,
                    schedule.Color,
                    1,
                    schedule.Location,
                    ""
                };

            }
            return JsonHelper.ToJson(cje);

        }
        
        
        /// <summary>
        /// 获得日程列表  JSON格式 用于列表视图
        /// </summary>
        /// <param name="showdate"></param>
        /// <param name="viewtype"></param>
        /// <returns></returns>
        private string ListCalendarJsionDateForListView()
        {
            HttpContext context = System.Web.HttpContext.Current;
            BLL_CALENDAR bll = new BLL_CALENDAR();
            Grid<Entity_SME_Schedule> grid = new Grid<Entity_SME_Schedule>();
            Entity_SME_Schedule calendar = new Entity_SME_Schedule();
            calendar.UserId = userId;
            calendar.Title = context.Request.Params["Title"];
            calendar.StartTime = context.Request.Params["StartTime"];
            calendar.EndTime = context.Request.Params["EndTime"];
            calendar.Status = isLdCalendar ? 3 : -1;
            int currentPage = Convert.ToInt16(context.Request.Params["page"]);
            int pageSize = Convert.ToInt16(context.Request.Params["rows"]);
            List<Entity_SME_Schedule> list = bll.getSchedulePaginationList(calendar,currentPage,pageSize);
            grid.rows = list;
            grid.total = bll.getAllCount(calendar);
            return JsonHelper.ToJson(grid);
        }


        /// <summary>
        /// 快速更新日程 
        /// </summary>
        /// <param name="calendarId"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public string UpdateCalendar(string calendarId, string startTime, string endTime)
        {
            DAL_SME_SCHEDULE dss = new DAL_SME_SCHEDULE();
            Entity_SME_Schedule calendar = new Entity_SME_Schedule();
            calendar.SceID = decimal.Parse(calendarId);
            calendar.StartTime = startTime;
            calendar.EndTime = endTime;
            calendar.ModifyUserId = SystemContext.CurrentUserID;
            bool isSuccess = false;
            Hashtable ht = new Hashtable();
            try
            {
                isSuccess = dss.quicktUpdate(calendar);
                if (isSuccess)
                {

                    ht.Add("IsSuccess", true);
                    ht.Add("Msg", "保存成功！");
                }
                else
                {
                    ht.Add("IsSuccess", false);
                    ht.Add("Msg", "保存失败!");
                }
            }
            catch (Exception e)
            {
                ht.Add("IsSuccess", false);
                ht.Add("Msg", "保存失败！" + e.Message);
            }
            return JsonHelper.ToJson(ht);
        }


        /// <summary>
        /// 快速添加日程
        /// </summary>
        /// <returns></returns>
        public string AddCalendar()
        {
            Entity_SME_Schedule calendar = new Entity_SME_Schedule();
            calendar.UserId = userId;
            calendar.Title = _context.Request.Params["CalendarTitle"];
            calendar.StartTime = _context.Request.Params["CalendarStartTime"];
            calendar.EndTime = _context.Request.Params["CalendarEndTime"];
            calendar.IsAllDayEvent = decimal.Parse(_context.Request.Params["IsAllDayEvent"]);
            calendar.Content = "";
            calendar.Color = "-1";
            calendar.Location = "";
            calendar.CreateUserId = SystemContext.CurrentUserID;
            calendar.Status = isLdCalendar ? 3 : 1;
            DAL_SME_SCHEDULE dss = new DAL_SME_SCHEDULE();
            bool isSuccess = false; ;

            Hashtable ht = new Hashtable();
            try
            {
                isSuccess = dss.SaveSchedule(calendar);
                if (isSuccess)
                {

                    ht.Add("IsSuccess", true);
                    ht.Add("Msg", "保存成功！");
                }
                else
                {
                    ht.Add("IsSuccess", false);
                    ht.Add("Msg", "保存失败!");
                }
            }
            catch (Exception e)
            {
                ht.Add("IsSuccess", false);
                ht.Add("Msg", "保存失败！" + e.Message);
                AppLog.Write("---异常位置:Calendarfeer.addCalendar()---", AppLog.LogMessageType.Error, e);
            }
            return JsonHelper.ToJson(ht);
        }

        /// <summary>
        /// 详细日程添加
        /// </summary>
        /// <returns></returns>
        public string AddDetailedCalendar()
        {
            Entity_SME_Schedule calendar = getCalendarDetailed();
            calendar.UserId = userId;
            calendar.CreateUserId = SystemContext.CurrentUserID;
            DAL_SME_SCHEDULE dss = new DAL_SME_SCHEDULE();
            bool isSuccess = false; ;

            Hashtable ht = new Hashtable();
            try
            {
                isSuccess = dss.SaveSchedule(calendar);
                if (isSuccess)
                {
                    if (calendar.IsSms == 1) saveOrUpdateSmsReady(0, calendar);
                    ht.Add("IsSuccess", true);
                    ht.Add("Msg", "保存成功！");
                }
                else
                {
                    ht.Add("IsSuccess", false);
                    ht.Add("Msg", "保存失败!");
                }
            }
            catch (Exception e)
            {
                ht.Add("IsSuccess", false);
                ht.Add("Msg", "保存失败！" + e.Message);
                AppLog.Write("---异常位置:Calendarfeer.UpdateDetailedCalendar()---", AppLog.LogMessageType.Error, e);
            }
            return JsonHelper.ToJson(ht);
        }


        /// <summary>
        /// 详细日程更新
        /// </summary>
        /// <returns></returns>
        public string UpdateDetailedCalendar(decimal id)
        {
            Entity_SME_Schedule calendar = getCalendarDetailed();
            calendar.ModifyUserId = SystemContext.CurrentUserID;
            
            DAL_SME_SCHEDULE dss = new DAL_SME_SCHEDULE();
            bool isSuccess = false; ;

            Hashtable ht = new Hashtable();
            try
            {
                isSuccess = dss.updateScheduleById(id, calendar);
                if (isSuccess)
                {
                    if (calendar.IsSms == 1) saveOrUpdateSmsReady(id, calendar);
                    else this.deleteSmsReady(id);
                    ht.Add("IsSuccess", true);
                    ht.Add("Msg", "保存成功！");
                }
                else
                {
                    ht.Add("IsSuccess", false);
                    ht.Add("Msg", "保存失败!");
                }
            }
            catch (Exception e)
            {
                ht.Add("IsSuccess", false);
                ht.Add("Msg", "保存失败！" + e.Message);
                AppLog.Write("---异常位置:Calendarfeer.UpdateDetailedCalendar()---", AppLog.LogMessageType.Error, e);
            }
            return JsonHelper.ToJson(ht);
        }
        


        /// <summary>
        /// 删除日程
        /// </summary>
        /// <param name="calendarId"></param>
        /// <returns></returns>
        public string RemoveCalendar(string calendarId)
        {
            DAL_SME_SCHEDULE dss = new DAL_SME_SCHEDULE();
            bool isSuccess = false; ;

            Hashtable ht = new Hashtable();
            try
            {
                isSuccess = dss.deleteScheduleById(long.Parse(calendarId));
                if (isSuccess)
                {

                    ht.Add("IsSuccess", true);
                    ht.Add("Msg", "删除成功！");
                }
                else
                {
                    ht.Add("IsSuccess", false);
                    ht.Add("Msg", "删除失败!");
                }
            }
            catch (Exception e)
            {
                ht.Add("IsSuccess", false);
                ht.Add("Msg", "删除失败！" + e.Message);
                AppLog.Write("---异常位置:Calendarfeer.RemoveCalendar()---", AppLog.LogMessageType.Error, e);
            }
            return JsonHelper.ToJson(ht);
        }
        
        /// <summary>
        /// 保存或更新短信提醒
        /// </summary>
        /// <param name="calendarId"></param>
        /// <param name="calendar"></param>
        /// <returns></returns>
        public string saveOrUpdateSmsReady(decimal calendarId, Entity_SME_Schedule calendar)
        {
            bool isSave = calendarId == 0 ? true : false ;

            Entity_USER_User toUser = null;
            
            int sendType = Convert.ToInt16(_context.Request.Params["smsSendType"]);
            calendarId = calendarId == 0 ? new DAL_SME_SCHEDULE().getIdentCurrent() : calendarId;
            Entity_COM_Sms_Ready smsReady = new Entity_COM_Sms_Ready();
            smsReady.RdyFromUserID = SystemContext.CurrentUserID;
            smsReady.RdyToUserID = isLdCalendar ? userId : SystemContext.CurrentUserID;
            smsReady.RdyAccessType = "SME_SCHEDULE";
            smsReady.RdyAccessValue = calendarId;
            smsReady.RdySendTime = calendar.StartTime.Replace("/","-");
            smsReady.RdyReadySendTime = calendar.StartTime.Replace("/", "-");
            smsReady.RdySendType = sendType;
            smsReady.RdySendFlag = 0;
            
            toUser = new DAL_USER_User().getUserByUserID(smsReady.RdyToUserID);
            smsReady.RdyMtnumber = toUser.MobilePhone;
            
            if (sendType == 1)
            {
                smsReady.RdyReadySendTime = _context.Request.Params["smsSendDate"].Replace("/","-") + " " + _context.Request.Params["smsSendHour"] +":"+ _context.Request.Params["smsSendMinute"];
            }
            else if(sendType == 2)
            {
                smsReady.RdyBeforeMinute = Convert.ToInt16(_context.Request.Params["smsBeforeMinute"]);
            }

            smsReady.RdyTextContent = this.SmsPriview(calendar);

            BLL_SmsOperation bllSmsReady = new BLL_SmsOperation();
            
            try
            {
                if (isSave)
                {
                    bllSmsReady.addSmsReday(smsReady);
                }
                else
                {
                    Entity_COM_Sms_Ready sr = getSmsReadyCalendarId(calendarId);
                    //短信已存在并且未发送则更新
                    if (sr != null && sr.RdySendFlag == 0)
                    {
                        bllSmsReady.updateSmsReadyBySRIDAndSREntity(sr.RdyID, smsReady);
                    }
                    else if (sr == null)
                    {
                        bllSmsReady.addSmsReday(smsReady);
                    }
                    else
                    { 
                        //无法更新，短信已发送
                    }
                }
            }
            catch(Exception e)
            {
                AppLog.Write(e.Message,AppLog.LogMessageType.Error);
            }
            
            return "";
        }
        
        /// <summary>
        /// 删除短信提醒
        /// </summary>
        /// <param name="calendarId"></param>
        public void deleteSmsReady(decimal calendarId)
        {
            BLL_SmsOperation bllSmsReady = new BLL_SmsOperation();
            if(calendarId != 0)
            {
                bllSmsReady.deleteSmsReadyByCalendarID(calendarId);
            }
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="calendarId"></param>
        /// <returns></returns>
        public Entity_COM_Sms_Ready getSmsReadyCalendarId(decimal calendarId)
        {
            BLL_SmsOperation bllSmsReady = new BLL_SmsOperation();
            Entity_COM_Sms_Ready smsReady = new Entity_COM_Sms_Ready();
            smsReady.RdyAccessType = "SME_SCHEDULE";
            smsReady.RdyAccessValue = calendarId;
            List <Entity_COM_Sms_Ready> list = bllSmsReady.getSmsReadyListBysmsRdyEntity(smsReady);
            if (list.Count > 0) return list[0];
            return null;
        }

        /// <summary>
        /// 短息预览
        /// </summary>
        /// <returns></returns>
        public string SmsPriview(Entity_SME_Schedule calendar)
        {
            string rdyTextContent = "";
            Entity_USER_User toUser = new DAL_USER_User().getUserByUserID(isLdCalendar ? userId : SystemContext.CurrentUserID);
            string StartTime = "";
            string EndTime = "";
            
            string rdyTimeStr = "";
            DateTime startDate = DateTimeUtil.String2Date(calendar.StartTime);
            DateTime endDate = DateTimeUtil.String2Date(calendar.EndTime);
            if (calendar.IsAllDayEvent == 0)
            {
                StartTime = DateTimeUtil.Date2String(startDate, "MM月dd日HH时mm分");
                if (startDate.Day == endDate.Day)
                {
                    EndTime = DateTimeUtil.Date2String(DateTimeUtil.String2Date(calendar.EndTime), "HH时mm分");
                }
                else
                {
                    EndTime = DateTimeUtil.Date2String(DateTimeUtil.String2Date(calendar.EndTime), "MM月dd日HH时mm分");
                }
                rdyTimeStr = StartTime +"至"+EndTime;
            }
            else 
            {
                StartTime = DateTimeUtil.Date2String(startDate, "MM月dd日");
                rdyTimeStr = StartTime;
            }
            
            //全天日程
            if(calendar.NoEndTime == 1)
            {
                rdyTimeStr = StartTime;
            }
            
            //短信内容
            if (isLdCalendar)
            {
                int currentHour = DateTimeUtil.String2Date(calendar.StartTime).Hour;
                string howHello = "";
                if(currentHour >= 6 && currentHour <= 12){
                    howHello = "上午";
                }else if(currentHour > 12 && currentHour <= 14 ){
                    howHello = "中午";
                }else if(currentHour >14 && currentHour <= 18){
                    howHello = "下午";
                }else if(currentHour > 18 && currentHour <= 20){
                    howHello = "傍晚";
                }else if(currentHour > 20 && currentHour <= 23){
                    howHello = "晚上";
                }else {
                    howHello = "凌晨";
                }
                howHello = calendar.IsAllDayEvent == 0 ? howHello+"好，" : "您好，";
                
                StringBuilder textContent = new StringBuilder();
                textContent.Append("日程提醒：")
                            .Append(toUser.Backup1)
                            .Append(howHello)
                            .Append(rdyTimeStr);
                if(calendar.Location != null && calendar.Location.Length > 0)
                {
                    textContent.Append("在").Append(calendar.Location);
                }
                else
                {
                    textContent.Append("-");
                }
                            
                textContent.Append(calendar.Title);
                rdyTextContent = textContent.ToString();
            }
            else
            {
                rdyTextContent = "日程提醒：" + rdyTimeStr;
                if (calendar.Location != null && calendar.Location.Trim().Length > 0)
                {
                    rdyTextContent = rdyTextContent + "在" + calendar.Location;
                }
                else
                {
                    rdyTextContent = rdyTextContent + "-";
                }
                
                rdyTextContent = rdyTextContent+ calendar.Title;
                
            }
            return rdyTextContent;
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private Entity_SME_Schedule getCalendarDetailed()
        {
            Entity_SME_Schedule calendar = new Entity_SME_Schedule();
            calendar.UserId = userId;
            calendar.Title = _context.Request.Params["Subject"];
            calendar.StartTime = _context.Request.Params["stpartdate"] + " " + _context.Request.Params["stpartHour"] + ":" + _context.Request.Params["stpartMinute"];
            calendar.EndTime = _context.Request.Params["etpartdate"] + " " + _context.Request.Params["etpartHour"] + ":" + _context.Request.Params["etpartMinute"];
            calendar.IsAllDayEvent = _context.Request.Params["IsAllDayEvent"] == null ? 0 : 1;
            if (_context.Request.Params["NoEndTime"] != null)
            {
                calendar.NoEndTime = 1;
                calendar.Color = "13";
            }
            else
            {
                calendar.Color = _context.Request.Params["colorvalue"];
            }
            calendar.Content = _context.Request.Params["Description"];
            
            calendar.Location = _context.Request.Params["Location"];
            calendar.Status = Convert.ToDecimal(_context.Request.Params["status"]);
            calendar.IsSms = Convert.ToInt16(_context.Request.Params["isSms"]);
            return calendar;
        }
        
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}